<?php
/**
 * Create by 11li
 * Date 2020/1/9
 * Time 21:36
 *
 */

namespace app\common\service;


use app\common\model\Address;

class AddressService extends BaseService
{
	
	public function saveAddress($userId, $data) {
		$model = new Address();
		
		//查看是否有默认地址
		$default = $model->where(['user_id' => $userId, 'is_default' => 1, 'status' => StatusService::STATUS_NORMAL])->find();
		if(!$default) {
			$data['is_default'] = 1;
		}
		
		if(!empty($data['is_default']) && $data['is_default'] == 1) {
			$model->save(['is_default' => 0], ['user_id' => $userId]);
		}
		
		$id = !empty($data['id']) ? $data['id'] : '';
		$data['user_id'] = $userId;
		if($id) {
			unset($data['id']);
			$res = $model->allowField(true)->save($data, ['id' => $id, 'user_id' => $userId]);
		} else {
			$res = $model->allowField(true)->isUpdate(false)->save($data);
		}
		
		return $res;
	}
}